package com.ebelter.temperaturegun.model.http;


import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.ebelter.btcomlib.CommonLib;
import com.ebelter.btcomlib.common.Constants;
import com.ebelter.btcomlib.models.beans.UpdateVersionBean;
import com.ebelter.btcomlib.models.https.HttpsUrl;
import com.ebelter.btcomlib.models.https.IHttpRequestField;
import com.ebelter.btcomlib.models.https.MyStringCallback;
import com.ebelter.btcomlib.models.https.NetUtils;
import com.ebelter.btcomlib.models.https.interfaces.HttpResponse;
import com.ebelter.btcomlib.models.https.responses.BaseResponse;
import com.ebelter.btcomlib.models.https.responses.GetTempertureData;
import com.ebelter.btcomlib.models.https.responses.GetTempertureData2;
import com.ebelter.btcomlib.models.https.responses.GetTempertureData3;
import com.ebelter.btcomlib.models.https.responses.LoginResponse;
import com.ebelter.btcomlib.models.https.responses.RegisterResponse;
import com.ebelter.btcomlib.models.https.responses.getEmailValidateCodeResponse;
import com.ebelter.btcomlib.utils.AppUtils;
import com.ebelter.btcomlib.utils.GsonUtils;
import com.ebelter.btcomlib.utils.ToastUtil;
import com.ebelter.btcomlib.utils.UserSpUtil;
import com.ebelter.btcomlib.utils.ViewUtils;
import com.ebelter.btcomlib.utils.log.LogUtils;
import com.ebelter.temperaturegun.R;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Response;

public class TGNetUtils {
    private static final String TAG = "TGNetUtils";
    private BaseJsonGenerator mBaseJsonGenerator;
    private TGNetUtils(){mBaseJsonGenerator=new BaseJsonGenerator();}

    private static TGNetUtils instance;

    public static TGNetUtils getInstance() {
        if (instance==null){
            synchronized (TGNetUtils.class){
                if (instance==null){
                    instance = new TGNetUtils();
                }
            }
        }
        return instance;
    }


//    //网络是否可用
//    public boolean available(){
//        ConnectivityManager connectivity = (ConnectivityManager) CommonLib.APPContext.getSystemService(Context.CONNECTIVITY_SERVICE);
//        if (connectivity == null) {
//            return false;
//        } else {
//            NetworkInfo[] info = connectivity.getAllNetworkInfo();
//            if (info != null) {
//                for (NetworkInfo anInfo : info) {
//                    if (anInfo.getState() == NetworkInfo.State.CONNECTED) {
//                        if (anInfo.getType() == ConnectivityManager.TYPE_WIFI) {
//                            return true;
//                        } else if (anInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
//                            return true;
//                        }
//                    }
//                }
//            }
//        }
//        return false;
//    }


    public void getFileDownLoad(Object tag, String url, FileCallback fileCallback){
        OkGo.get(url).tag(tag).execute(fileCallback);
    }


    public void cancelTag(Object tag){
        OkGo.getInstance().cancelTag(tag);
    }
    /**
     * post请求获取数据
     */
    public void post(Object tag, String url, StringCallback callback){
        post(tag,url,null,callback);
    }
    /**
     * post请求获取数据
     */
    public  void post(Object tag, String url, HttpParams httpParams, StringCallback callback){
        OkGo.post(url).tag(tag).params(httpParams).execute(callback);
    }

    /**
     * postJson请求获取数据
     */
    public void postJson(Object tag, String url, String requestJson, StringCallback callback){
        OkGo.post(url).tag(tag).upJson(requestJson).execute(callback);
    }



    static final String  R_S_R_S = "请求成功,解析成功";
    static final String  R_S_R_F = "请求成功，解析失败";
    static final String  R_F = "请求失败";



    /**
     * 注册用户
     * @param birthday 1991-09-13
     * @param height 176
     * @param weight 65
     * @param code 邮箱验证码
     * @param type type=1 注册 type=2 忘记密码
     */
    public void registerRequest(Object tag, String nickName, String email, String password,
                                String birthday, int height, int weight, int sex,int profession,
                                String code, int type,
                                final HttpResponse<RegisterResponse> httpResponse){
        String registerjson=mBaseJsonGenerator.getRegisterRJ(nickName, email, password, birthday, height, weight,sex,profession, code, type);
       // LogUtils.i(TAG,"注册Json："+registerjson);
        postJson(tag, HttpsUrl.registerUrl,registerjson ,
                new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        RegisterResponse res= GsonUtils.getInstance().fromJson(s,RegisterResponse.class);
                        if (res!=null){
                            httpResponse.result(true,R_S_R_S,res,s);
                        }else {
                            httpResponse.result(false,R_S_R_F,null,s);
                        }
                    }
                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        httpResponse.result(false,R_F,null,null);
                    }
                }
        );
    }


    //获取邮箱验证码 type=1 注册 type=2 忘记密码
    public void getEmailValidateCodeRequest(Object tag, String email, int type, final HttpResponse<getEmailValidateCodeResponse> httpResponse){
        postJson(tag, HttpsUrl.getEmailValidateCodeUrl, mBaseJsonGenerator.getEmailValidateRJ(email, type, AppUtils.getLocalStr()),
                new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        getEmailValidateCodeResponse res=GsonUtils.getInstance().fromJson(s,getEmailValidateCodeResponse.class);
                        if (res!=null){
                            httpResponse.result(true,R_S_R_S,res,s);
                        }else {
                            httpResponse.result(false,R_S_R_F,null,s);
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        httpResponse.result(false,R_F,null,null);
                    }
                }
        );
    }


    //更新密码
    public void findPassWord(Object tag, String email, String newPassword, String code, final HttpResponse<BaseResponse> httpResponse){
        // paramMap.put(HttpsParameters.USER_ID, UserSpUtil.readLong(Constants.IUser.USER_ID));
        Map<String,Serializable> paramMap=new HashMap<>();
        paramMap.put("email",email);
        paramMap.put("newPassword",newPassword);
        paramMap.put("code",code);
        postJson(tag, HttpsUrl.updatePasswordUrl, mBaseJsonGenerator.getMapRJ(paramMap), new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {

                BaseResponse res=GsonUtils.getInstance().fromJson(s,BaseResponse.class);
                if (res!=null){
                    httpResponse.result(true,R_S_R_S,res,s);
                }else {
                    httpResponse.result(false,R_S_R_F,null,s);
                }
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                httpResponse.result(false,R_F,null,null);
            }

        });
    }


    /**
     *
     * 登录请求
     * @param isLoginEmail 是否是邮箱登录
     * @param loginStr 登录的字符串
     * @param psw MD5加密的密码
     * @param httpResponse 返回请求
     */
    public void loginRequest(Object tag, boolean isLoginEmail, String loginStr, String psw, final HttpResponse<LoginResponse> httpResponse){
        String loginRJ = mBaseJsonGenerator.getLoginRJ(isLoginEmail,loginStr,psw);
        // ULog.i(TAG,"登录的json："+loginRJ);
        postJson(tag,HttpsUrl.loginUrl,loginRJ,
                new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        LoginResponse res=GsonUtils.getInstance().fromJson(s,LoginResponse.class);
                        if (res!=null){
                            httpResponse.result(true,R_S_R_S,res,s);
                        }else {
                            httpResponse.result(false,R_S_R_F,null,s);
                        }
                    }
                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        httpResponse.result(false,R_F,null,null);
                    }
                }
        );
    }



    //上传体温
    //tempType:温度类型(1:耳温,2:额温),不传默认耳温
    public void uploadTem(Object tag,long userId,float temperature,int tempType,String testTime,final HttpResponse<BaseResponse> httpResponse){
        Map<String,Serializable> paramMap=new HashMap<>();
        paramMap.put("userId",userId);
        paramMap.put("temperature",temperature);
        paramMap.put("tempType",tempType);
        paramMap.put("testDate",testTime);
        String json = mBaseJsonGenerator.getMapRJ(paramMap);

        postJson(tag,HttpsUrl.upLoadTempertureDatas,json,
                new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        LoginResponse res=GsonUtils.getInstance().fromJson(s,LoginResponse.class);
                        if (res!=null){
                            httpResponse.result(true,R_S_R_S,res,s);
                        }else {
                            httpResponse.result(false,R_S_R_F,null,s);
                        }
                    }
                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        httpResponse.result(false,R_F,null,null);
                    }
                }
        );

    }


    /**体温历史数据分页查询（/get/page/data）
     * @param startPage 起始页
     * @param pageSize 返回的页数
     * tempType 温度类型(1:耳温,2:额温)
     */
    public void getTempertureData1(Object tag,long userId,int startPage,int pageSize,int tempType,HttpResponse<GetTempertureData> httpResponse){
        Map<String,Serializable> paramMap=new HashMap<>();
        paramMap.put(IHttpRequestField.USER_ID, userId);
        paramMap.put(IHttpRequestField.START_INDEX, startPage);
        paramMap.put(IHttpRequestField.PAGE_SIZE, pageSize);
        paramMap.put("tempType", tempType);
        String json = mBaseJsonGenerator.getMapRJ(paramMap);
        postJson(tag, HttpsUrl.getTempertureDatas, json, new MyStringCallback(httpResponse,GetTempertureData.class));
    }

    /**体温历史数据分页查询（/get/page/data）
     * @param startPage 起始页
     * @param pageSize 返回的页数
     * tempType 温度类型(1:耳温,2:额温)
     */
    public void getTempertureData13(Object tag,long userId,int startPage,int pageSize,HttpResponse<GetTempertureData> httpResponse){
        Map<String,Serializable> paramMap=new HashMap<>();
        paramMap.put(IHttpRequestField.USER_ID, userId);
        paramMap.put(IHttpRequestField.START_INDEX, startPage);
        paramMap.put(IHttpRequestField.PAGE_SIZE, pageSize);
        String json = mBaseJsonGenerator.getMapRJ(paramMap);
        postJson(tag, HttpsUrl.getTempertureDatas, json, new MyStringCallback(httpResponse,GetTempertureData.class));
    }


    /**体温历史数据分页查询（/get/page/data）
     * tempType 温度类型(1:耳温,2:额温)
     */
    public void getTempertureData12(Object tag,long userId,int tempType,String startTime,String endTime,
                                    HttpResponse<GetTempertureData> httpResponse){
        Map<String,Serializable> paramMap=new HashMap<>();
        paramMap.put(IHttpRequestField.USER_ID, userId);
        paramMap.put(IHttpRequestField.START_INDEX, 0);
        paramMap.put(IHttpRequestField.PAGE_SIZE, 10000);
        paramMap.put("startTime", startTime);
        paramMap.put("endTime", endTime);
        paramMap.put("tempType", tempType);
        String json = mBaseJsonGenerator.getMapRJ(paramMap);
        postJson(tag, HttpsUrl.getTempertureDatas, json, new MyStringCallback(httpResponse,GetTempertureData.class));
    }


    /**
     *体温历史数据近期对比查询（/get/late/data）
     */
    public void getTempertureData2(Object tag,long userId,String testDate,HttpResponse<GetTempertureData2> httpResponse){
        Map<String,Serializable> paramMap=new HashMap<>();
        paramMap.put(IHttpRequestField.USER_ID, userId);
        paramMap.put(IHttpRequestField.testDate,testDate);
        String json = mBaseJsonGenerator.getMapRJ(paramMap);
        postJson(tag, HttpsUrl.getTempertureDatas2, json, new MyStringCallback(httpResponse,GetTempertureData2.class));
    }


    /**
     * @param tempType 温度类型(1:耳温,2:额温)
     */
    public void getEveryDayLastDatas(Object tag,long userId,int tempType,int startIndex,
                                    HttpResponse<GetTempertureData3> httpResponse){
        Map<String,Serializable> paramMap=new HashMap<>();
        paramMap.put(IHttpRequestField.USER_ID, userId);
        paramMap.put("tempType", tempType);
        paramMap.put("startIndex", startIndex);
        paramMap.put("pageSize", 30);
        String json = mBaseJsonGenerator.getMapRJ(paramMap);
        postJson(tag, HttpsUrl.getTempertureDatas3, json, new MyStringCallback(httpResponse,GetTempertureData3.class));
    }


    public void getUpdateVersionJson(Object tag, final HttpResponse<UpdateVersionBean> httpResponse){
        OkGo.post("http://o.ebelter.com/apk_update/temperaturegun_apk/version.json").tag(tag).execute(new MyStringCallback<>(httpResponse,UpdateVersionBean.class));
    }

    //更新用户信息
    public void updateInfo(Object tag,Map<String, Serializable> paramMap, HttpResponse<BaseResponse> httpResponse){
        String json=mBaseJsonGenerator.getMapRJ(paramMap);
        postJson(tag, HttpsUrl.updateInfoUrl, json, new MyStringCallback(httpResponse,BaseResponse.class));
    }


}
